package com.google.code.sharecontent.action;

import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.End;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

import com.google.code.sharecontent.model.Content;
import com.google.code.sharecontent.model.Playlist;

@Scope(ScopeType.CONVERSATION)
@Name("myplaylists")
public class MyPlaylistsAction extends BaseAction {


	@In("daoAction")
	private DaoAction daoAction;
	
	@In("scanApplication")
	private ScanApplication scanApplication;
	
    @In
    private FacesContext facesContext;
    
    private Integer selectedPlaylistId;

    
    public void addPublicPlaylist() {
    	
    }
    
    public void editPlaylist(Integer id) {
    	this.setSelectedPlaylistId(id);
    }
    
    public void addMyPlaylist() {
    	
    }
    
    public List<Playlist> getList() {
    	log.info("generate all playlists");
    	List<Playlist> list = null;
		try {
			list = daoAction.getPlaylistDao().list();
		} catch (SQLException e) {
			log.error(e.getMessage());
		}
    	return list;
    }
    
    /**
     * FIXME remove this!
     */
	public void generateAllPlayList() {
//		#EXTM3U
//		#EXTINF:315,DJ Грув - Любочка
//		\\Test\media\{  Наше  }\{Попса}\DJ Грув\00-Lubochka.mp3
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        response.setContentType("audio/x-mpegurl");
        response.addHeader("Content-disposition", "attachment; filename=\"data.m3u\"");
        response.addHeader("Cache-Control", "no-cache");
        response.setStatus(200);
        try {
            // committing status and headers
            response.flushBuffer();
            PrintWriter writer = new PrintWriter(response.getOutputStream());
            writer.println("#EXTM3U");
            List<Content> listContents = this.daoAction.getContentDao().list(
    				" STATUS_ID=" + scanApplication.getStatusActive().getId() + "", "ID");
            for (Content te : listContents) {
                writer.println("#EXTINF:"+te.getId()+","+te.getArtist()+" - "+te.getTitle());
                writer.println(te.getUrl());
            }
            writer.close();

        } catch (Exception e) {
            // ignore for test
        }
        facesContext.responseComplete();
	}
	
	@Begin
	public void start() {
		log.info(" start");
	}
	
	@End
	public void end() {
		log.info(" end");
	}

	public void setSelectedPlaylistId(Integer selectedPlaylistId) {
		this.selectedPlaylistId = selectedPlaylistId;
	}

	public Integer getSelectedPlaylistId() {
		return selectedPlaylistId;
	}

}
